package Thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Thread_drawMoney {
    public static void main(String[] args) {
        Account account = new Account("360281", 100000);
        new DrawMoney(account).start();
        new DrawMoney(account).start();
    }
}
class DrawMoney extends Thread {
    private Account account;
    public DrawMoney(){}
    public DrawMoney(Account account) {
        super(account.getAccount());//直接把参数传入父类
        this.account=account;
    }
    @Override
    public void run() {
        account.drawMoney(100000);
    }
}
class Account{
    private String account;
    private int money;
    private Lock lock=new ReentrantLock();//声明该类的一把同步锁

    public Account(String account, int money) {
        this.account = account;
        this.money = money;
    }
    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    synchronized //同步方法  防止发生线程安全问题 默认当前类对象为唯一标识,如果是静态方法的话就默认 类名.class 为唯一标识
    public int getMoney() {
        lock.lock();//手动锁住
        lock.unlock();//手动解锁
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
    public void drawMoney(double money){
        synchronized (this) {//同步代码块 防止发生线程安全问题
            if(this.money>=money){
                System.out.println("...");
                System.out.println("...");
                System.out.println("...");
                System.out.println(Thread.currentThread().getName()+"成功");
                this.money-=money;
                System.out.println("余额："+this.money);
                System.out.println();
            }else {
                System.out.println(Thread.currentThread().getName()+"失败余额："+this.money);
            }
        }
    }
}

